<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i>
                    {{pageTitle}}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box flex flex-center">
                <el-button type="primary" icon="el-icon-folder" @click="submitForm('ruleForm')">保存</el-button>
            </div>
            <div class="table-form-box">
                <h3 class="h3">考核模板</h3>
                <el-form :model="formData" :rules="rules" ref="ruleForm">
                    <table border="0" width="100%" cellpadding="0" cellspacing="1">
                        <tbody>
                            <tr>
                                <td align="right">
                                    <span class="color-ff2200">*</span>考核类别:
                                </td>
                                <td>
                                    <el-form-item prop="templateTypeId">
                                        <el-select
                                            v-model="formData.templateTypeId"
                                            placeholder="请选择"
                                            @change="handleValue($event,'考核类别')"
                                            @focus="dictItemForPerfection('考核类别')"
                                        >
                                            <el-option
                                                v-for="(item,index) in templateTypeOption"
                                                :key="index"
                                                :label="item.itemName"
                                                :value="item.id"
                                            ></el-option>
                                        </el-select>
                                    </el-form-item>
                                </td>
                                <td align="right">
                                    <span class="color-ff2200">*</span>模板名称:
                                </td>
                                <td>
                                    <el-form-item prop="templateName">
                                        <el-input
                                            placeholder="请输入内容"
                                            v-model="formData.templateName"
                                            clearable
                                        ></el-input>
                                    </el-form-item>
                                </td>
                                <td align="right">创建人:</td>
                                <td>
                                    <el-form-item prop="createUserName">
                                        <el-input
                                            placeholder="请输入内容"
                                            v-model="formData.createUserName"
                                            disabled
                                        ></el-input>
                                    </el-form-item>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </el-form>

                <div style="margin-top:10px;border:1px solid">
                    <div style="margin:10px;">
                        <vxe-toolbar>
                            <template v-slot:buttons>
                                <vxe-button
                                    status="primary"
                                    icon="fa fa-plus"
                                    @click="insertEvent(-1)"
                                >新增行</vxe-button>
                                <vxe-button status="danger" @click="deleteCheckBoxRow()">删除选中行</vxe-button>
                            </template>
                        </vxe-toolbar>

                        <vxe-table
                            keep-source
                            stripe
                            border
                            show-footer
                            :footer-method="footerMethod"
                            resizable
                            ref="xTable"
                            :data="tableData"
                            :edit-rules="validRules"
                            :edit-config="{trigger: 'click', mode: 'cell'}"
                        >
                            <vxe-table-column type="checkbox" width="60"></vxe-table-column>
                            <vxe-table-column  field="itemName"
                                title="考核项"  type="seq" width="60"  :edit-render="{name: '$input', props: {type: 'number',min:0,max:999}}"></vxe-table-column>
                            <vxe-table-column
                                field="itemName"
                                title="考核项"
                                :edit-render="{name: 'input', attrs: {type: 'text'}}"
                            ></vxe-table-column>
                            <vxe-table-column
                                field="points"
                                title="分数"
                                :edit-render="{name: '$input', props: {type: 'number',min:0,max:999}}"
                            ></vxe-table-column>
                            <vxe-table-column
                                field="description"
                                title="考核说明"
                                :edit-render="{name: 'input', attrs: {type: 'text'}}"
                            ></vxe-table-column>
                            <vxe-table-column title="自评分数"></vxe-table-column>
                            <vxe-table-column title="上级评分"></vxe-table-column>
                        </vxe-table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import appMain from '../../../utils/app_main';
import XEUtils from 'xe-utils';
export default {
    name: 'transfer',
    data() {
        return {
            pageTitle: '',
            formData: {
                assessmentPoints: '', //总分
                templateName: '', //福利编码
                templateTypeId: '', //模板类型
                templateTypeName: '', //模板类型名称
                templateTypeValue: '', //模板类型
                createUserName: '',
                createUserId: '',
                assessmentItemDTOList: [] //考核项信息
            },
            rules: {
                templateTypeId: [
                    {
                        required: true,
                        message: '请选择',
                        trigger: 'change'
                    }
                ],
                templateName: [
                    {
                        required: true,
                        message: '请输入内容',
                        trigger: 'change'
                    },
                    {
                        min: 0,
                        max: 200,
                        message: '长度在 2 到 200 个字符',
                        trigger: 'change'
                    }
                ]
            },
            validRules: {
                itemName: [{ required: true, message: '考核项必须填写' }],
                points: [
                    { required: true, message: '考核分数必须填写' },
                    { pattern: '^[0-9]{0,3}$', message: '格式不正确' }
                ],
                description: [
                    { required: true, message: '考核说明必须填写' },
                    { min: 2, max: 300, message: '长度在 2 到 300 个字符' }
                ]
            },
            flag: false,
            isEdit: false,
            editId: '',
            //调动类型
            templateTypeOption: [],
            tableData: []
        };
    },
    created() {
        // 如果有id就是跳转过来修改的
        this.dictItemForPerfection('考核类别');
        if (this.$route.query.id) {
            this.editId = this.$route.query.id;
            this.isEdit = true;
            this.getData(); // 获取要修改的数据
        } else {
            this.resetTableData();
            //TODO 获取登录时存在vux的用户名和id
            this.formData.createUserName = this.$store.state.userData.username;
            this.formData.createUserId = this.$store.state.userData.id;
            this.isEdit = false;
            this.flag = true;
        }
    },
    methods: {
        //初始化table
        resetTableData() {
            const length = this.tableData.length;
            if (length < 10) {
                for (let index = 10; index > length; index--) {
                    let record = {
                        description: '',
                        itemName: '',
                        points: ''
                    };
                    this.tableData.push(record);
                }
            }
            console.log('resetTableData', this.tableData);
        },

        getData() {
            appMain
                .assessmentTemplateFindById({}, this.editId)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.formData = res.data.data;
                        this.tableData = res.data.data.assessmentItemDTOList;
                        //获取人员档案附件
                        //this.uploadFileInfoFindById(this.formData.id);
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    if (this.isEdit) {
                        this.updateTemplate();
                    } else {
                        this.updateValidEvent();
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        /**
         * 下拉框数据start
         */
        dictItemForPerfection(item) {
            appMain.dictItem({ typeName: item }).then(res => {
                if (res.data.code === 20000) {
                    if (item == '考核类别') {
                        this.templateTypeOption = res.data.data;
                    }
                } else {
                    this.$message.error(res.data.message);
                }
            });
        },
        //下拉框选取值
        handleValue(e, dict) {
            if (dict == '考核类别') {
                let item = this.selectChooseItem(this.templateTypeOption, e);
                this.formData.templateTypeId = item.id;
                this.formData.templateTypeName = item.itemName;
                this.formData.templateTypeValue = item.itemValue;
            }
        },
        //通用字典选择
        selectChooseItem(item, id) {
            for (const key in item) {
                if (item[key].id == id) {
                    return item[key];
                }
            }
        },
        /**
         * 下拉框获取end
         */
        /**vxe-table */
        async insertEvent(row) {
            let record = {
                description: '',
                itemName: '',
                points: ''
            };
            let { row: newRow } = await this.$refs.xTable.insertAt(record, row);
            //await this.$refs.xTable.setActiveCell(newRow, 'sex');
            console.log('insertEvent', this.tableData);
        },
        //删除选中列
        deleteCheckBoxRow() {
            let selectRecords = this.$refs.xTable.getCheckboxRecords();
            if (selectRecords.length < 1) {
                this.$message({
                    message: '请选择一条数据',
                    type: 'info'
                });
            } else {
                this.$refs.xTable.removeCheckboxRow();
                this.tableData = this.$refs.xTable.tableData;
            }
        },
        //新增考核模板
        async updateValidEvent() {
            let updateRecords = this.$refs.xTable.tableData;
            if (updateRecords.length > 0) {
                const errMap = await this.$refs.xTable.validate(updateRecords).catch(errMap => errMap);
                if (errMap) {
                    //this.$XModal.message({ status: 'error', message: '请按要求完成评测！' });
                    this.$message.warning('请按要求完成评测！');
                } else {
                    //this.$XModal.message({ status: 'success', message: '校验成功！' });
                    let params = this.formData;

                    params.assessmentItemDTOList = updateRecords;

                    console.log('updateRecords', updateRecords);

                    appMain
                        .assessmentTemplateInsert(params)
                        .then(res => {
                            if (res.data.code === 20000) {
                                if (this.isEdit) {
                                    this.getData();
                                }
                                this.$router.push({
                                    path: '/assessmentList' //跳转的路径
                                });
                                this.$message({
                                    message: res.data.message,
                                    type: 'success'
                                });
                            } else {
                                this.$message({
                                    message: res.data.message,
                                    type: 'error'
                                });
                            }
                        })
                        .catch(err => {
                            console.log(err);
                        });
                    console.log(this.$router);
                }
            } else {
                //this.$XModal.message({ status: 'warning', message: '未选中数据！' });
                this.$message.info('无更新数据');
            }
        },
        //更新模板
        async updateTemplate() {
            console.log('updateTemplate', this.tableData);
            if (this.tableData.length > 0) {
                const errMap = await this.$refs.xTable.fullValidate().catch(errMap => errMap);
                if (errMap) {
                    //this.$XModal.message({ status: 'error', message: '请按要求完成评测！' });
                    this.$message.warning('请填写完毕');
                } else {
                   // this.$XModal.message({ status: 'success', message: '校验成功！' });
                    let params = this.formData;
                    params.assessmentItemDTOList = this.$refs.xTable.tableData;
                    appMain
                        .assessmentTemplateUpdateById(params)
                        .then(res => {
                            if (res.data.code === 20000) {
                                if (this.isEdit) {
                                    this.getData();
                                }
                                this.$router.push({
                                    path: '/assessmentList' //跳转的路径
                                });
                                this.$message({
                                    message: res.data.message,
                                    type: 'success'
                                });
                            } else {
                                this.$message({
                                    message: res.data.message,
                                    type: 'error'
                                });
                            }
                        })
                        .catch(err => {
                            console.log(err);
                        });
                    console.log(this.$router);
                }
            } else {
                //this.$XModal.message({ status: 'warning', message: '未选中数据！' });
                this.$message.info('无更新数据');
            }
        },
        //表脚
        footerMethod({ columns, data }) {
            return [
                columns.map((column, columnIndex) => {
                    if (columnIndex === 0) {
                        return '合计';
                    }
                    if (columnIndex === 3) {
                        //console.log('columns', data);
                        let coin = `${XEUtils.sum(data, 'points')}`;
                        this.formData.assessmentPoints = coin;
                        return '考核总分:' + coin + ' 分';
                    }
                    return '-';
                })
            ];
        }
    },
    mounted() {
        this.pageTitle = this.$router.currentRoute.meta.title;
    }
};
</script>

<style scoped>
.container {
    padding-bottom: 50px;
}
.handle-box {
    padding: 5px 50px;
    width: 100%;
    background-color: #fff;
    position: absolute;
    left: 0;
    bottom: 0px;
    border-bottom: 1px solid #ddd;
    border-top: 1px solid #ddd;
    z-index: 1;
}

.table {
    width: 100%;
    font-size: 14px;
}

.table-form-box table {
    background-color: #666;
}
.table-form-box .h3 {
    font-size: 22px;
    text-align: center;
    font-weight: normal;
    padding: 20px 0;
}
.table-form-box table .tr-title td {
    font-size: 14px;
    line-height: 40px;
}
.table-form-box table td,
.table-form-box table th {
    background-color: #fff;
    padding: 4px;
    min-height: 40px;
    font-size: 12px;
}
.color-ff2200 {
    color: #ff2200;
}
</style>
